package com.ja.openchat.ui.contact;

import static com.ja.openchat.ui.SplashActivity.REQUEST_BASIC;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.gson.JsonObject;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.contact.Section;
import com.zy.openchat.core.model.contact.SectionInfo;
import com.zy.openchat.core.model.user.MobileContactInfo;
import com.zy.openchat.core.model.user.OrgUserInfo;
import com.zy.openchat.core.model.user.UserInfo;
import com.ja.openchat.databinding.FragmentMobileContactHomeBinding;
import com.zy.openchat.util.Common;
import com.zy.openchat.util.ContactUtils;
import com.ja.openchat.viewmodels.MobileContactViewModel;
import com.ja.openchat.views.CustomEditText;
import com.ja.openchat.views.SideIndexBar;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.goldze.mvvmhabit.base.BaseFragment;
import me.goldze.mvvmhabit.utils.ToastUtils;
import pub.devrel.easypermissions.EasyPermissions;

public class MobileContactFragment extends BaseFragment<FragmentMobileContactHomeBinding, MobileContactViewModel> {

    private int chooseType = 0;
    private String[] permissList = {Manifest.permission.READ_CONTACTS, Manifest.permission.READ_PHONE_STATE};
    private List<Section> sectionList = new ArrayList<>();
    private List<UserInfo> localList = new ArrayList<>();
    private List<UserInfo> totalList = new ArrayList<>();
    private List<UserInfo> tempList;
    private MobileContactListAdapter contactListAdapter;

    private boolean isMobile(){
        return chooseType == 0;
    }
    private ArrayList<UserInfo> mChooseUserInfos;
    private CircleUserAdapter circleUserAdapter;


    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_mobile_contact_home;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }


    @Override
    public void initView() {
        super.initView();
        viewModel.setContext(getActivity());

        if(getActivity().getIntent()!=null){
            chooseType = getActivity().getIntent().getIntExtra("chooseType",0);
        }
        if(getActivity().getIntent()!=null&&getActivity().getIntent().getSerializableExtra("choose")!=null){
            ArrayList<UserInfo> chatInfos = (ArrayList<UserInfo>)getActivity().getIntent().getSerializableExtra("choose");
            mChooseUserInfos = chatInfos;
        }


        UserInfo user = UserInfo.getUserInfo();
        binding.phoneIntroText.setText(String.format(getString(R.string.your_phone_number), Common.formatPhoneNumber(user.phone_number)));
        binding.uploadContact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!EasyPermissions.hasPermissions(getActivity(), permissList)){
                    EasyPermissions.requestPermissions(getActivity(),
                            String.format(getActivity().getString(R.string.permission_basic_tip), getActivity().getString(R.string.app_name)),
                            REQUEST_BASIC, permissList);
                }else{
                    handleContact();
                }
            }
        });


        showContacts();
    }

    private void showContacts() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        binding.recyclerView.setLayoutManager(layoutManager);
        contactListAdapter = new MobileContactListAdapter( sectionList);
        contactListAdapter.setChooseType(chooseType);
        binding.recyclerView.setAdapter(contactListAdapter);

        requestContacts(false);

        //同步联系人
        TelegramManager.getTelegramManager().syncMyContacts();

        contactListAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if (sectionList != null && sectionList.size() > 0 && position >= 0 && position < sectionList.size()) {
                    Section section = sectionList.get(position);
                    Object obj = section.getObject();
                    if (obj instanceof UserInfo) {
                        UserInfo user = (UserInfo) obj;
                        if(chooseType == 2||chooseType == -2||chooseType == 3){
                            section.setChecked(!section.isChecked());
                            if(section.isChecked()){
                                mChooseUserInfos.add(0,user);
                            }else{
                                if(!mChooseUserInfos.remove(user)){
                                    if(mChooseUserInfos!=null&&mChooseUserInfos.size()>0){
                                        for(UserInfo userInfo:mChooseUserInfos){
                                            if(userInfo.id == user.id){
                                                mChooseUserInfos.remove(userInfo);
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                            circleUserAdapter.notifyDataSetChanged();
                            contactListAdapter.notifyItemChanged(position);
                            return;
                        }
                        if(isMobile()){
                            //跳转个人资料详情
//                            ContactDetailActivity.start(MobileContactHomeActivity.this, user);
                        }else{
                            Intent intent = new Intent();
                            intent.putExtra("user",user);
//                            setResult(Activity.RESULT_OK,intent);
//                            finish();
                        }
                    }
                }
            }
        });

        binding.etSearch.setOnXTextChangeListener(new CustomEditText.OnXTextChangeListener() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                doSearch(s.toString());
            }
        });

        if(chooseType == 2||chooseType == -2||chooseType == 3){
            if(mChooseUserInfos==null){
                mChooseUserInfos = new ArrayList<>();
            }
//            circleUserAdapter = new CircleUserAdapter(mChooseUserInfos);
//            binding.userRecyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false));
//            binding.userRecyclerView.setAdapter(circleUserAdapter);
//            binding.userRecyclerView.setVisibility(View.VISIBLE);
//            tv_ok_right.setVisibility(View.VISIBLE);
//            tv_ok_right.setText("确定");
//            tv_ok_right.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    if(chooseType == 2||chooseType == -2){
//                        saveTag();
//                    }else{
//                        Intent intent = new Intent();
//                        intent.putExtra("users",mChooseUserInfos);
//                        setResult(Activity.RESULT_OK,intent);
//                        finish();
//                    }
//                }
//            });
        }
    }


    public void doSearch(String keyword){
        if(TextUtils.isEmpty(keyword)){
            resetList(totalList);
            return;
        }
        localList.clear();
        if(totalList!=null&&totalList.size()>0){
            for(UserInfo userInfo:totalList){
                if(!TextUtils.isEmpty(userInfo.displayName())&&userInfo.displayName().contains(keyword)){
                    localList.add(userInfo);
                }else if(!TextUtils.isEmpty(userInfo.realDisplayName)&&userInfo.realDisplayName.contains(keyword)){
                    localList.add(userInfo);
                }
            }
        }
        resetList(localList);
    }

    private void requestContacts(boolean isHint){
        tempList = TelegramManager.getTelegramManager().getTgData().getMyContacts();
        if(tempList!=null&&tempList.size()>0){
            List<UserInfo> userInfos = new ArrayList<>();
            List<MobileContactInfo> contactInfos = ContactUtils.getIntance().getHasUserIdContactInfos();
            List<Long> userIds = new ArrayList<>();
            if(isMobile()){
                if(contactInfos!=null&&contactInfos.size()>0){
                    for(MobileContactInfo contactInfo:contactInfos){
                        for(UserInfo userInfo:tempList){
                            if(contactInfo.user_id == userInfo.id){
                                userIds.add(userInfo.id);
                                userInfos.add(userInfo);
                                break;
                            }
                        }
                    }
                }
                tempList = userInfos;
            }else{
                for(UserInfo userInfo:tempList){
                    userIds.add(userInfo.id);
                }
            }
            if(Common.isEmpty(userIds)){
                if(isHint){
                    ToastUtils.showShort(getString(R.string.no_content_yet));
                }
                reloadContacts(tempList);
                return;
            }
            TelegramManager.getTelegramManager().requestOrgContactInfos(getActivity(), userIds, new TgResultBlock<List<OrgUserInfo>>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, List<OrgUserInfo> obj) {
                    if(obj!=null&&obj.size()>=tempList.size()){
                        for(OrgUserInfo orgUserInfo:obj){
                            for(UserInfo userInfo:tempList){
                                if(userInfo.id == orgUserInfo.uId){
                                    userInfo.realDisplayName = orgUserInfo.displayName();
                                    break;
                                }
                            }
                        }
//                        for(int i = 0;i<tempList.size();i++){
//                            UserInfo userInfo = tempList.get(i);
//                            OrgUserInfo orgUserInfo = obj.get(i);
//
//                            if(i<obj.size()){
//                                userInfo.realDisplayName = obj.get(i).displayName();
//                            }
//                        }
                    }
                    reloadContacts(tempList);
                }

                @Override
                public void onTimeout(Map<String, Object> request) {
                    reloadContacts(tempList);
                }
            });
        }else{
            reloadContacts(tempList);
        }
    }

    private void reloadContacts(List<UserInfo> list) {
        if(Common.isEmpty(list)){
            return;
        }
        //排序
        if (list.size() > 1) {
            Collections.sort(list, new Comparator<UserInfo>() {
                @Override
                public int compare(UserInfo u1, UserInfo u2) {
                    if (!StringUtils.isEmpty(u1.displayName_full_py) && !StringUtils.isEmpty(u2.displayName_full_py)) {
                        return u1.displayName_full_py.compareTo(u2.displayName_full_py);
                    }
                    return 0;
                }
            });
        }
        totalList.clear();
        totalList.addAll(list);
        resetList(list);
    }

    private void resetList(List<UserInfo> list){
        if(list==null){
            return;
        }
        sectionList.clear();
        Map<String, List<UserInfo>> sectionMap = new HashMap<>();
        for (String azIndex : SideIndexBar.DEFAULT_INDEX_ITEMS_1) {
            sectionMap.put(azIndex, new ArrayList<>());
        }

        //插入userinfo
        for (UserInfo user : list) {
            if (!StringUtils.isEmpty(user.displayName_full_py)) {
                if (sectionMap.get(String.valueOf(user.displayName_full_py.toUpperCase().charAt(0))) != null) {
                    sectionMap.get(String.valueOf(user.displayName_full_py.toUpperCase().charAt(0))).add(user);
                } else {
                    sectionMap.get("#").add(user);
                }
            } else {
                sectionMap.get("#").add(user);
            }
        }
        //ui数据
        for (String azIndex : SideIndexBar.DEFAULT_INDEX_ITEMS_1) {
            if (sectionMap.get(azIndex).size() > 0) {
                sectionList.add(new Section(true, new SectionInfo(azIndex)));
                for (UserInfo user : sectionMap.get(azIndex)) {
                    boolean isChecked = false;
                    if(mChooseUserInfos!=null&&mChooseUserInfos.size()>0){
                        for(UserInfo userInfo:mChooseUserInfos){
                            if(userInfo.id == user.id){
                                isChecked = true;
                                break;
                            }
                        }
                    }
                    sectionList.add(new Section(false, user,isChecked));
                }
            }
        }

        if(!sectionList.isEmpty()){
            binding.layoutUploadContact.setVisibility(View.GONE);
            binding.layoutAlreadyUploadContact.setVisibility(View.VISIBLE);
            //刷新页面
            contactListAdapter.notifyDataSetChanged();
        }else{
            binding.layoutUploadContact.setVisibility(View.VISIBLE);
            binding.layoutAlreadyUploadContact.setVisibility(View.GONE);
        }

    }


    private void handleContact(){
        showDialog();
        ArrayList<MobileContactInfo> contactInfos =  ContactUtils.getIntance().getAllContacts(getActivity());
        if(contactInfos==null||contactInfos.size()==0){
            dismissDialog();
            requestContacts(true);
            return;
        }
        TelegramManager.getTelegramManager().importContacts(getActivity(),contactInfos, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                dismissDialog();
                if(obj.ok){
                    ContactUtils.getIntance().setContactInfos(contactInfos);
                }
                requestContacts(true);
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                dismissDialog();
                ToastUtils.showShort(getString(R.string.request_error));
                requestContacts(false);
            }
        });
    }
}
